package com.cch.utils;

//import com.cch.platform.util.DateUtil;
import com.cch.enums.WeekDayEnum;
import com.cch.stock.set.bean.SdStock;
import com.cch.stock.set.bean.SdStockDaliy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetDataFromSina {

//	private final String SINA_FINANCE_URL = "http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradehistory.php?symbol=sh600497&date=2017-04-13";
	private final String SINA_FINANCE_URL = "http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradehistory.php";
	private static final String CURR_TIME_FINANCE_URL = "http://hq.sinajs.cn/list=";

	/**
	 *  历史数据，不含今天数据
	 * @param stock
	 * @param from
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public ArrayList<SdStockDaliy> getStockCsvData(SdStock stock, Date from, Date to){
		ArrayList<SdStockDaliy> list = new ArrayList<SdStockDaliy>();
		int i=0;
		while (true){
			Date date = DateUtil.getNextNDate(from,i);
			if(WeekDayEnum.SUN.equals(DateUtil.getWeekDayEnumFromDate(date))||WeekDayEnum.SAT.equals(DateUtil.getWeekDayEnumFromDate(date))){
				continue;
			}
			if(date.after(to)){
				break;
			}
			String url=this.getHistoryUrl(stock, date);
			try {
				list.add(createSdStockDaliy(HttpClientUtils.doGet(url),stock.getStockCode(),date));
			}catch (Exception e){

			}
			i++;
		}
		return list;
	}

	private SdStockDaliy createSdStockDaliy(HttpResult httpResult,String stockCode ,Date date) {

		if (httpResult.isSuccess()) {

			String body = httpResult.getBody();
			Document doc = Jsoup.parse(body);
			//id="dp_wrap"
			Element element =doc.getElementById("quote_area");
			Elements elements = element.select("table").select("tr");
			List<String>   valList = new ArrayList<String>();
			for (int i = 0; i < elements.size(); i++) {
				Element element1 = elements.get(i);
				String value= element1.select("td").get(1).select("span").size()>0?element1.select("td").get(1).select("span").html():element1.select("td").get(1).html();
				valList.add(value);
			}
			SdStockDaliy sdStockDaliy = new SdStockDaliy(valList);
			sdStockDaliy.setStockCode(stockCode);
			sdStockDaliy.setReDate(date);
			return sdStockDaliy;
		}
		return null;
	}


	/**
	 * ===================================================
	 * 创建url
	 * ===================================================
	 * 参数
	 *  s – 股票代码
	 *  ?symbol=sh600497&date=2017-04-13";
	 */
	private String getHistoryUrl(SdStock stock,Date date){
		String dateStr = DateUtil.dateToStr(date, DateUtil.YEAR_MONTH_DATE);

		StringBuffer url = new StringBuffer(SINA_FINANCE_URL);
		url.append("?symbol=" +stock.getStockMarket()+ stock.getStockCode());
		url.append("&date=").append(dateStr);
		return url.toString();
	}

	/**
	 * Date,Open,High,Low,Close,Volume,Adj Close
	 * @param line
	 * @return
	 * @throws java.text.ParseException
	 */
	private SdStockDaliy createObject(SdStock stock, String line) throws ParseException {
		SdStockDaliy sd=new SdStockDaliy();
		String[] data = line.trim().split(",");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		sd.setStockCode(stock.getStockCode());
		sd.setReDate(sdf.parse(data[0]));
		sd.setPriceOpen(Double.parseDouble(data[1]));
		sd.setPriceHigh(Double.parseDouble(data[2]));
		sd.setpriceLow(Double.parseDouble(data[3]));
		sd.setVolume(Long.parseLong(data[5]));
		sd.setPriceClose(Double.parseDouble(data[6]));
		return sd;
	}

	public static void main(String[] args) {
//		String url = CURR_TIME_FINANCE_URL+"sz300116";
		GetDataFromSina sina =new GetDataFromSina();
		SdStock sdStock =new SdStock();//, "sz300116"
		sdStock.setStockCode("300116");
		sdStock.setStockMarket("sz");
		String url=sina.getHistoryUrl(sdStock,DateUtil.convertDateStringToDate(DateUtil.ALL, DateUtil.getYesterdayStr()));
		HttpResult ss = HttpClientUtils.doGet(url);

		if(ss.isSuccess()){
			String body = ss.getBody();
			Document doc = Jsoup.parse(body);
			//id="dp_wrap"
			Element element =doc.getElementById("quote_area");
			Elements elements = element.select("table").select("tr");
			for (int i = 0; i < elements.size(); i++) {
				Element element1 = elements.get(i);
				String value= element1.select("td").get(1).select("span").size()>0?element1.select("td").get(1).select("span").html():element1.select("td").get(1).html();
				System.out.println(value);
			}
		}

	}
}